"""
模拟数据生成器

提供各种测试场景所需的模拟数据。
"""

import random
import string
from datetime import datetime, timedelta
from typing import List, Dict, Any, Optional
from faker import Faker


class MockDataFactory:
    """模拟数据工厂类"""

    def __init__(self, locale: str = 'zh_CN'):
        self.fake = Faker(locale)
        random.seed(42)  # 确保数据的可重复性

    def create_module(self, **overrides) -> Dict[str, Any]:
        """创建单个模块的模拟数据"""
        module = {
            'id': f"module_{self.fake.random_int(min=1000, max=9999)}",
            'name': self.fake.catch_phrase(),
            'type': random.choice(['shared_library', 'static_library', 'executable', 'kernel_module']),
            'subsystem': random.choice(['foundation', 'ace', 'arkui', 'hiview', 'multimedia']),
            'componentName': random.choice(['bundlemanager', 'samgr', 'ability_base', 'render_service']),
            'modGroup': random.choice(['system', 'app', 'driver', 'kernel', 'third-party']),
            'deps_total': self.fake.random_int(min=0, max=50),
            'deps_indirect': self.fake.random_int(min=0, max=100),
            'deps_self': self.fake.random_int(min=0, max=20),
            'dependedBy': self.fake.random_int(min=0, max=30),
            'dependedBy_total': self.fake.random_int(min=0, max=50),
            'depth': self.fake.random_int(min=1, max=10),
            'provided': self.fake.random_int(min=0, max=200),
            'used': self.fake.random_int(min=0, max=150),
            'needed': self.fake.random_int(min=0, max=100),
            'matched': self.fake.random_int(min=0, max=80),
            'duplicated': self.fake.random_int(min=0, max=20),
            'unmatched': self.fake.random_int(min=0, max=30),
            'size': self.fake.random_int(min=1024, max=104857600),  # 1KB - 100MB
            'text_size': self.fake.random_int(min=512, max=52428800),
            'data_size': self.fake.random_int(min=256, max=26214400),
            'bss_size': self.fake.random_int(min=128, max=13107200),
            'path': f"/system/lib64/{self.fake.word()}.so",
            'labelPath': f"//{self.fake.word()}/{self.fake.word()}:{self.fake.word()}",
            'human_size': self._format_size(self.fake.random_int(min=1024, max=104857600)),
            'processes': self.fake.random_int(min=1, max=10),
            'Pss': self.fake.random_int(min=1024, max=10485760),
            'swapPss': self.fake.random_int(min=0, max=1048576),
            'Shared_Dirty': self.fake.random_int(min=0, max=1048576),
            'Private_Dirty': self.fake.random_int(min=0, max=1048576),
            'napi': random.choice([True, False]),
            'innerapi': random.choice([True, False]),
            'third_party': random.choice([True, False]),
            'chipset': random.choice([True, False]),
            'platformsdk': random.choice([True, False]),
            'chipsetsdk': random.choice([True, False]),
            'hdiType': random.choice(['interface', 'callback', 'service', 'client']),
            'shlib_type': random.choice(['dynamic', 'static']),
            'innerapi_tags': ','.join(random.sample(['audio', 'video', 'network', 'graphics', 'security'], random.randint(1, 3))),
            'right_tags': ','.join(random.sample(['read', 'write', 'execute', 'admin'], random.randint(1, 2))),
            'unused': self.fake.random_int(min=0, max=50)
        }

        # 应用覆盖值
        module.update(overrides)
        return module

    def create_modules_list(self, count: int = 20) -> List[Dict[str, Any]]:
        """创建模块列表的模拟数据"""
        modules = []
        subsystems = ['foundation', 'ace', 'arkui', 'hiview', 'multimedia', 'communication', 'graphic']
        types = ['shared_library', 'static_library', 'executable', 'kernel_module']
        groups = ['system', 'app', 'driver', 'kernel', 'third-party']

        for i in range(count):
            module = self.create_module()
            # 确保数据多样性
            module['subsystem'] = subsystems[i % len(subsystems)]
            module['type'] = types[i % len(types)]
            module['modGroup'] = groups[i % len(groups)]
            module['name'] = f"TestModule_{i+1:03d}_{self.fake.word()}"
            modules.append(module)

        return modules

    def create_module_array_format(self, count: int = 20) -> List[List]:
        """创建后端数组格式的模块数据"""
        modules = []
        for i, module in enumerate(self.create_modules_list(count)):
            # 转换为后端返回的数组格式
            array_module = [
                module['id'],                    # 0: id
                module['type'],                  # 1: type
                module['subsystem'],             # 2: subsystem
                module['componentName'],         # 3: component
                module['name'],                  # 4: name
                module['modGroup'],              # 5: modGroup
                module['deps_total'],            # 6: deps_total
                module['deps_indirect'],         # 7: deps_indirect
                module['deps_self'],             # 8: deps_self
                module['dependedBy'],            # 9: dependedBy
                module['depth'],                 # 10: depth
                module['provided'],              # 11: provided
                module['used'],                  # 12: used
                module['needed'],                # 13: needed
                module['matched'],               # 14: matched
                module['duplicated'],            # 15: duplicated
                module['unmatched'],             # 16: unmatched
                None,                            # 17: (placeholder)
                None,                            # 18: (placeholder)
                None,                            # 19: (placeholder)
                None,                            # 20: (placeholder)
                None,                            # 21: (placeholder)
                None,                            # 22: (placeholder)
                None,                            # 23: (placeholder)
                module['size'],                  # 24: size
                module['text_size'],             # 25: text_size
                module['data_size'],             # 26: data_size
                module['bss_size'],              # 27: bss_size
                None,                            # 28: (placeholder)
                None,                            # 29: (placeholder)
                None,                            # 30: (placeholder)
                None,                            # 31: (placeholder)
                None,                            # 32: (placeholder)
                None,                            # 33: (placeholder)
                None,                            # 34: (placeholder)
                module['path'],                  # 35: path
                module['labelPath']              # 36: labelPath
            ]
            modules.append(array_module)

        return modules

    def create_product_data(self, name: str = "aln", versions: List[str] = None) -> Dict[str, Any]:
        """创建产品数据的模拟"""
        if versions is None:
            versions = ["1119", "1120", "1121", "2000"]

        return {
            'name': name,
            'display_name': f"OpenHarmony {name.upper()}",
            'description': f"OpenHarmony {name.upper()} Product",
            'versions': versions,
            'current_version': versions[0],
            'created_at': self.fake.date_time_this_year(),
            'updated_at': self.fake.date_time_this_month()
        }

    def create_api_response(self, data: Any, success: bool = True, message: str = "Success") -> Dict[str, Any]:
        """创建 API 响应的模拟数据"""
        response = {
            'success': success,
            'message': message,
            'data': data,
            'timestamp': datetime.now().isoformat()
        }

        if not success:
            response['error'] = {
                'code': 'TEST_ERROR',
                'details': message
            }

        return response

    def create_dependency_data(self, module_id: str, depth: int = 3) -> Dict[str, Any]:
        """创建依赖关系的模拟数据"""
        dependencies = []
        for i in range(random.randint(1, 10)):
            dep = {
                'from': module_id,
                'to': f"module_{self.fake.random_int(min=1000, max=9999)}",
                'type': random.choice(['direct', 'indirect']),
                'strength': random.uniform(0.1, 1.0),
                'depth': random.randint(1, depth)
            }
            dependencies.append(dep)

        return {
            'module_id': module_id,
            'dependencies': dependencies,
            'total_count': len(dependencies),
            'max_depth': depth
        }

    def create_symbol_data(self, module_id: str) -> Dict[str, Any]:
        """创建符号信息的模拟数据"""
        symbols = []
        symbol_types = ['function', 'variable', 'class', 'enum', 'typedef']

        for i in range(random.randint(10, 50)):
            symbol = {
                'name': f"{self.fake.word()}_{i}",
                'type': random.choice(symbol_types),
                'visibility': random.choice(['global', 'local', 'static']),
                'defined': random.choice([True, False]),
                'size': self.fake.random_int(min=4, max=1024),
                'address': f"0x{random.randint(0x1000, 0xFFFFFF):08x}"
            }
            symbols.append(symbol)

        return {
            'module_id': module_id,
            'symbols': symbols,
            'total_count': len(symbols),
            'exported': random.randint(5, len(symbols))
        }

    def create_memory_data(self, module_id: str) -> Dict[str, Any]:
        """创建内存使用数据的模拟"""
        return {
            'module_id': module_id,
            'memory_info': {
                'vm_size': self.fake.random_int(min=1024, max=102400),
                'rss': self.fake.random_int(min=512, max=51200),
                'pss': self.fake.random_int(min=256, max=25600),
                'shared_clean': self.fake.random_int(min=128, max=12800),
                'shared_dirty': self.fake.random_int(min=64, max=6400),
                'private_clean': self.fake.random_int(min=32, max=3200),
                'private_dirty': self.fake.random_int(min=16, max=1600),
                'swap': self.fake.random_int(min=0, max=800),
                'swap_pss': self.fake.random_int(min=0, max=400)
            },
            'processes': [
                {
                    'pid': self.fake.random_int(min=1000, max=9999),
                    'name': self.fake.word(),
                    'memory_usage': self.fake.random_int(min=1024, max=10240)
                }
                for _ in range(random.randint(1, 5))
            ]
        }

    def create_chart_data(self, chart_type: str = "bar", data_points: int = 10) -> Dict[str, Any]:
        """创建图表数据的模拟"""
        labels = [f"Item_{i+1}" for i in range(data_points)]

        if chart_type == "bar":
            datasets = [{
                'label': 'Test Data',
                'data': [self.fake.random_int(min=10, max=100) for _ in range(data_points)],
                'backgroundColor': [
                    f"rgba({random.randint(0, 255)}, {random.randint(0, 255)}, {random.randint(0, 255)}, 0.6)"
                    for _ in range(data_points)
                ]
            }]
        elif chart_type == "line":
            datasets = [{
                'label': 'Test Trend',
                'data': [self.fake.random_int(min=10, max=100) for _ in range(data_points)],
                'borderColor': f"rgb({random.randint(0, 255)}, {random.randint(0, 255)}, {random.randint(0, 255)})",
                'backgroundColor': f"rgba({random.randint(0, 255)}, {random.randint(0, 255)}, {random.randint(0, 255)}, 0.1)"
            }]
        elif chart_type == "pie":
            data = [self.fake.random_int(min=5, max=50) for _ in range(data_points)]
            total = sum(data)
            datasets = [{
                'data': data,
                'backgroundColor': [
                    f"rgba({random.randint(0, 255)}, {random.randint(0, 255)}, {random.randint(0, 255)}, 0.8)"
                    for _ in range(data_points)
                ]
            }]
            return {
                'labels': labels,
                'datasets': datasets,
                'total': total
            }
        else:
            datasets = []

        return {
            'labels': labels,
            'datasets': datasets
        }

    def create_error_data(self, error_type: str = "API_ERROR") -> Dict[str, Any]:
        """创建错误数据的模拟"""
        errors = {
            "API_ERROR": {
                'code': 500,
                'message': 'Internal Server Error',
                'details': 'An unexpected error occurred while processing your request'
            },
            "NETWORK_ERROR": {
                'code': 'NETWORK_ERROR',
                'message': 'Network Connection Failed',
                'details': 'Unable to connect to the server'
            },
            "VALIDATION_ERROR": {
                'code': 400,
                'message': 'Validation Error',
                'details': 'The provided data is invalid'
            },
            "NOT_FOUND": {
                'code': 404,
                'message': 'Resource Not Found',
                'details': 'The requested resource does not exist'
            }
        }

        return errors.get(error_type, errors["API_ERROR"])

    def _format_size(self, size_bytes: int) -> str:
        """格式化文件大小"""
        for unit in ['B', 'KB', 'MB', 'GB']:
            if size_bytes < 1024:
                return f"{size_bytes:.1f} {unit}"
            size_bytes /= 1024
        return f"{size_bytes:.1f} TB"

    def create_search_filters(self) -> Dict[str, Any]:
        """创建搜索过滤器的模拟数据"""
        return {
            'search': self.fake.word(),
            'type': random.choice(['shared_library', 'executable', '']),
            'component': random.choice(['bundlemanager', 'samgr', '']),
            'subsystem': random.choice(['foundation', 'ace', '']),
            'modGroup': random.choice(['system', 'app', '']),
            'sortBy': random.choice(['name', 'size', 'deps_total']),
            'sortOrder': random.choice(['asc', 'desc'])
        }

    def create_pagination_data(self, total_items: int = 100, page_size: int = 20, current_page: int = 1) -> Dict[str, Any]:
        """创建分页数据的模拟"""
        total_pages = (total_items + page_size - 1) // page_size
        start_item = (current_page - 1) * page_size + 1
        end_item = min(current_page * page_size, total_items)

        return {
            'total_items': total_items,
            'total_pages': total_pages,
            'current_page': current_page,
            'page_size': page_size,
            'start_item': start_item,
            'end_item': end_item,
            'has_next': current_page < total_pages,
            'has_prev': current_page > 1,
            'next_page': current_page + 1 if current_page < total_pages else None,
            'prev_page': current_page - 1 if current_page > 1 else None
        }